from datetime import datetime
from flask import Blueprint, request, current_app, g
from util.permission import permission_required
from util.result import Result
from models import db, Reader

# 创建读者管理的蓝图
api_bp = Blueprint('reader', __name__)


# 1. 创建读者接口（需要reader:create权限）
@api_bp.route('/reader', methods=['POST'])
@permission_required('reader:create')
def create_reader():
    try:
        data = request.get_json()
        if not data:
            return Result.error("请输入读者信息")

        # 验证必填字段
        required_fields = ['reader_no', 'name', 'gender', 'age', 'phone', 'reader_type']
        for field in required_fields:
            if field not in data or not str(data[field]).strip():
                return Result.error(f"{field} 是必填项")

        # 处理输入数据（去除首尾空格）
        reader_no = data.get('reader_no').strip()
        name = data.get('name').strip()
        gender = data.get('gender')
        age = data.get('age')
        phone = data.get('phone').strip()
        reader_type = data.get('type')

        # 检查读者ISBN编号是否已存在
        if Reader.query.filter_by(reader_no=reader_no).first():
            return Result.error("编号已存在")

        # 创建新读者
        new_reader = Reader(
            reader_no=reader_no,
            name=name,
            gender=gender,
            age=age,
            phone=phone,
            reader_type=reader_type,
            created_at=datetime.now(),
            updated_at=datetime.now()
        )

        db.session.add(new_reader)
        db.session.commit()

        return Result.success("读者创建成功")

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"创建读者异常: {str(e)}")
        return Result.error("创建读者失败，请稍后重试")


# 2. 分页查询读者接口（需要reader:read权限，支持筛选、排序）
@api_bp.route('/reader', methods=['GET'])
@permission_required('reader:read')
def search_reader():
    try:
        # 1. 获取分页参数（默认第1页，每页10条）
        page = request.args.get('page', type=int)  # 当前页码
        size = request.args.get('size', type=int)  # 每页条数
        # 页码和条数合法性校验
        if page < 1:
            page = 1
        if size < 1 or size > 100:  # 限制最大每页100条，避免性能问题
            size = 10

        # 2. 获取筛选参数
        kw = request.args.get('kw').strip()  # 名称模糊筛选
        reader_type = request.args.get('type').strip()

        # 3. 构建查询条件
        query = Reader.query
        if kw:
            query = query.filter((Reader.reader_no.like(f"%{kw}%")) |
                                 (Reader.name.like(f"%{kw}%")) |
                                 Reader.phone.like(f"%{kw}%"))

        if reader_type and reader_type != 'all':
            query = query.filter(Reader.reader_type.like(f"%{reader_type}%"))

        # 4. 构建排序条件（默认按编号倒序）
        query = query.order_by(Reader.reader_no.asc())

        # 5. 执行分页查询（SQLAlchemy内置分页方法）
        paginated_result = query.paginate(page=page, per_page=size, error_out=False)
        # 获取当前页数据
        readers = paginated_result.items

        # 6. 格式化返回数据
        result_list = [{
            "id": reader.id,
            "reader_no": reader.reader_no,
            "name": reader.name,
            "gender": reader.gender,
            "age": reader.age,
            "phone": reader.phone,
            "reader_type": reader.reader_type,
            "created_at": reader.created_at.strftime("%Y-%m-%d %H:%M:%S"),
            "updated_at": reader.updated_at.strftime("%Y-%m-%d %H:%M:%S")
        } for reader in readers]

        # 7. 构建分页响应体（包含分页元信息，方便前端渲染分页组件）
        page_data = {
            "total": paginated_result.total,  # 总记录数
            "page": page,  # 当前页码
            "size": size,  # 每页条数
            "list": result_list  # 当前页数据列表
        }

        return Result.success("分页查询成功", data=page_data)

    except Exception as e:
        current_app.logger.error(f"读者分页查询异常: {str(e)}")
        return Result.error("分页查询读者失败，请稍后重试")


# 3. 更新读者接口（需要reader:edit权限）
@api_bp.route('/reader', methods=['PUT'])
@permission_required('reader:update')
def update_reader():
    try:
        data = request.get_json()
        if not data:
            return Result.error("请输入更新信息")

        # 必须提供id才能更新
        reader_id = data.get('id')
        if not reader_id:
            return Result.error("请提供读者ID")

        # 查询指定ID的读者
        reader = Reader.query.get(reader_id)
        if not reader:
            return Result.error("未找到指定读者")

        # 检查读者编号是否重复
        if 'reader_no' in data and data['reader_no'] is not None:
            new_reader_no = str(data['reader_no']).strip()
            # 排除当前读者ID，检查是否有同名读者
            existing = Reader.query.filter(
                reader.reader_no == new_reader_no,
                reader.id != reader_id
            ).first()
            if existing:
                return Result.error("读者编号已存在")
            reader.reader_no = new_reader_no

        reader.name = str(data['name']).strip()
        reader.gender = data['gender']
        reader.age = data['age']
        reader.phone = str(data['phone']).strip()
        reader.reader_type = data['reader_type']
        # 修改读者的更新时间
        reader.updated_at = datetime.now()

        db.session.commit()
        return Result.success("读者更新成功")

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"更新读者异常: {str(e)}")
        return Result.error("更新读者失败，请稍后重试")


# 4. 删除读者接口（需要reader:delete权限）
@api_bp.route('/reader/<int:reader_id>', methods=['DELETE'])
@permission_required('reader:delete')
def delete_reader(reader_id):
    try:
        reader = Reader.query.get(reader_id)
        if not reader:
            return Result.error("读者不存在")

        db.session.delete(reader)
        db.session.commit()

        return Result.success("读者删除成功")

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"删除读者异常: {str(e)}")
        return Result.error("删除读者失败，请稍后重试")

# 5. 获取全部读者接口（需要reader:read权限）
@api_bp.route('/reader/all', methods=['GET'])
@permission_required('reader:read')
def all_book():
    try:
        data = [{
            "value": reader.id,
            "label": reader.name,
        } for reader in Reader.query.all()]
        return Result.success(data=data)

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"获取全部读者数据异常: {str(e)}")
        return Result.error("获取全部读者数据失败，请稍后重试")
